package com.chatplus.application.common.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.chatplus.application.common.enumeration.FileSizeUnit;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;

import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 文件处理工具类
 */
public class FileUtils extends FileUtil {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(FileUtils.class);

    private FileUtils() {
    }

    /**
     * 百分号编码工具方法
     *
     * @param s 需要百分号编码的字符串
     * @return 百分号编码后的字符串
     */
    public static String percentEncode(String s) {
        String encode = URLEncoder.encode(s, StandardCharsets.UTF_8);
        return encode.replaceAll("\\+", "%20");
    }

    public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) {
        String percentEncodedFileName = percentEncode(realFileName);

        String contentDispositionValue = "attachment; filename=" +
                percentEncodedFileName +
                ";" +
                "filename*=" +
                "utf-8''" +
                percentEncodedFileName;

        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
        response.setHeader("Content-disposition", contentDispositionValue);
        response.setHeader("download-filename", percentEncodedFileName);
    }

    public static String getBase64FromImageURL(String url) {
        try (HttpResponse response = HttpRequest.get(url).execute()) {
            InputStream inputStream = response.bodyStream();
            return Base64.encodeBase64String(inputStream.readAllBytes());

        } catch (Exception e) {
            LOGGER.message("图片链接转Base64失败").context("url", url).exception(e).error();
        }
        return null;
    }
    /**
     * 判断文件大小
     *
     * @param len  文件长度
     * @param size 限制大小
     * @param unit 限制单位（B,K,M,G）
     */
    public static boolean checkFileSize(Long len, int size, FileSizeUnit unit) {
        double fileSize = 0;
        switch (unit) {
            case BIT:
                fileSize = len;
                break;
            case KB:
                fileSize = (double) len / 1024;
                break;
            case MB:
                fileSize = (double) len / 1048576;
                break;
            case GB:
                fileSize = (double) len / 1073741824;
                break;
            default:
                break;
        }
        return fileSize <= size;
    }
}
